<template>
  <div class="chat-sidebar" :class="{'sidebar-open': isSidebarOpen, 'no-transition': isInitialRender}">
    <div class="sidebar-header">
      <div class="header-actions">
        <div class="toggle-sidebar nav-btn" v-if="isSidebarOpen" @click="toggleCollapse">
          <PanelLeftOpen size="20" color="var(--gray-800)"/>
        </div>
      </div>
    </div>
     <div ref="cesiumContainer" class="cesiumContainer"></div>


     <div class="homepage">
      <div class="header">
      <div class="layout-header">
        <div class="header-midden">
          <div class="cn">地质三维可视化与决策支持系统</div>
        </div>
        <div class="header-left">
        </div>
        <div class="header-right">
          <!-- <span>12:00:00</span>
          <span>2024-12-34</span>
          <span>Monday</span>
          <span>13°c</span> -->
        </div>
      </div>
    </div>

    <div class="tree">
      <LayerTree  v-show="isTreeVisible" @close="getClosed"/>
      <div class="toggle-button" @click="toggleTree" v-show="!isTreeVisible">
        <img :src="isTreeVisible?`/img/左展开.png`:`/img/左收起.png`" alt="Toggle Sidebar" />
      </div>
    </div>

      <Query  v-show="isShowQuery" @close="closeQuery"/>
    <div class="queryBtn" @click="isShowQuery = !isShowQuery" v-show="!isShowQuery">
      <img :src="isShowQuery?`/img/右展开.png`:`/img/右收起.png`"  />
    </div>
     </div>
    
  </div>
</template>

<script setup>
import { ref, computed, h,onMounted,getCurrentInstance } from 'vue';
import {
  DeleteOutlined,
  EditOutlined,
  MoreOutlined
} from '@ant-design/icons-vue';
import { message, Modal } from 'ant-design-vue';
import { PanelLeftClose, MessageSquarePlus ,PanelLeftOpen} from 'lucide-vue-next';
import "@/utils/PolylineTrailLinkMaterialProperty";
import { LayerManager } from "@/assets/modules/LayerManager";
import layerTreeData from "/public/data/tree-data.ts";
import LayerTree from "@/components/leftControl/LayerTree.vue";
import Query from "@/components/leftControl/queryIndex.vue";

const isTreeVisible = ref(true);
const isShowQuery = ref(false);
const instance = getCurrentInstance();
const EventBus = instance.appContext.config.globalProperties.EventBus;
const cesiumContainer = ref(null);
let viewer = null;
let layerManager = null;
const props = defineProps({
  isSidebarOpen: {
    type: Boolean,
    default: false
  },
});
let  cityDatabase =null
onMounted(async () => {
  console.log("cesium初始化");
  await initMap();
  initLayer();
  EventBus.on("toggle-Layer", toggleLayer);
  EventBus.on("cesium-command", useCommand);
  loadCityJson()
});
const emit = defineEmits(['toggleCesiumSidebar']);
const initMap = async () => {
   const ellipsoidTerrainProvider = new Cesium.EllipsoidTerrainProvider();
  
  viewer = new Cesium.Viewer(cesiumContainer.value, {
    infoBox: false, // 禁用 InfoBox
    geocoder: false, // 禁用 Geocoder
    homeButton: false,
    sceneModePicker: false,
    baseLayerPicker: false,
    navigationHelpButton: false,
    animation: false,
    timeline: false,
    fullscreenButton: false,
    contextOptions: {
      webgl: {
        alpha: true
      }
    },
    terrainProvider: ellipsoidTerrainProvider,
    // imageryProvider: imageryProvider,
  });
    let imageryProvider = new Cesium.UrlTemplateImageryProvider({
            url: "/globeWmts/{z}/{x}/{y}.png",
            minimumLevel: 0,
            maximumLevel: 8
        });
  viewer.imageryLayers.addImageryProvider(imageryProvider)
  // // 加载默认地形----------新版本加载方法
  // viewer.terrainProvider = await Cesium.createWorldTerrainAsync({
  //   requestWaterMask: true, // 请求水掩膜以实现水体效果
  //   requestVertexNormals: true // 请求法线以实现光照效果
  // });

  viewer.scene.globe.depthTestAgainstTerrain = false;
  viewer.scene.screenSpaceCameraController.maximumZoomDistance = 19000000;
  viewer._cesiumWidget._creditContainer.style.display = "none";
  // viewer.scene.debugShowFramesPerSecond = true;  //帧率显示
  viewer.scene.context.memoryThreshold = 12; //显存资源占用阈值,单位是GB。
  window.viewer = viewer;
   flyTo();
   loadBoundary()
};

const flyTo = () => {
  viewer.camera.setView({
    destination: {x: -3107440.293394754, y: 5278142.463558483, z: 3522667.7799246414},
    orientation: {
      heading:6.152298775399782,
      pitch: -1.1839944284389148,
      roll:0.000522794310955809
    }
  });
};
const toggleCollapse = () => {
  emit('toggleCesiumSidebar');
};
const loadBoundary = ()=>{
       var promise = Cesium.GeoJsonDataSource.load('./geojson/江苏省.json');
        promise.then(function (dataSource) {
            let entities = dataSource.entities.values;
            let positions = entities[0].polygon.hierarchy.getValue().positions
            const cartesianPositions = positions.map(p => new Cesium.Cartesian3(p.x, p.y, p.z));
            viewer.entities.add({
                polyline: {
                  positions: cartesianPositions,
                  width:2,
                  material: new Cesium.PolylineTrailLinkMaterialProperty(
                    Cesium.Color.YELLOW,
                    "./img/spriteline1.png",
                    10000
                  )
              }
           });
            viewer.entities.add({
               polyline: {
                  positions: cartesianPositions,
                  width:1,
                  material: Cesium.Color.YELLOW.withAlpha(0.6)
              }
           });
        });
     
}
const initLayer = async () => {
  layerManager = new LayerManager(viewer);
  await layerManager.loadLayersFromConfig(layerTreeData);
};
const toggleLayer = data => {
  debugger;
  let { layerIds, isShow } = data;
  if (!layerManager) return;
  for (let i = 0; i < layerIds.length; i++) {
    const layerId = layerIds[i];
     const layer = layerManager.getLayerById(layerId);
  if (layer) {
    layerManager.setLayerVisibility(layerId, isShow);
  } else {
    alert(
      `未找到名为 "${name}" 的图层，请检查数据文件中的 ID 是否为固定的 "${layerId}"`
    );
  }
  }
 
};


const toggleTree = () => {
  isTreeVisible.value = !isTreeVisible.value;
};
const toggleIcon = computed(() => {
  if (isTreeVisible.value) {
    // 树是可见的，显示“收缩”图标
    return require(`@/assets/image/左展开.png`);
  } else {
    // 树是隐藏的，显示“展开”图标
    return require(`@/assets/image/右展开.png`); // 请确保你有这张图片
  }
});
const getClosed=()=>{
  isTreeVisible.value = false 
}
const closeQuery=()=>{
  isShowQuery.value = false 
}

const loadCityJson =()=>{
fetch('/data/china-cities-jiangsu.json')
    .then(response => response.json())
    .then(data => {
        cityDatabase = data;
        console.log('江苏省城市数据库加载成功！');
    })
    .catch(error => console.error('加载本地城市数据库失败:', error));
}



const geocode_offline = landmarkName=> {
  const sortedLandmarks = Object.keys(cityDatabase).sort((a, b) => b.length - a.length);
    // 1. 尝试精确匹配 (最高优先级)
    if (cityDatabase[landmarkName]) {
        console.log(`精确匹配成功: '${landmarkName}'`);
        return cityDatabase[landmarkName];
    }

    // 2. 尝试模糊匹配 (例如用户说 "无锡市"，而数据库里是 "无锡")
    const cleanName = landmarkName.replace(/(市|县|区|村)$/, '');
    if (cityDatabase[cleanName]) {
        console.log(`清理后匹配成功: '${cleanName}'`);
        return cityDatabase[cleanName];
    }

    // 3. 尝试包含匹配 (核心！解决 "南京江宁" 的问题)
    for (const key of sortedLandmarks) {
        if (landmarkName.includes(key)) {
            console.log(`包含匹配成功: 在 '${landmarkName}' 中找到了 '${key}'`);
            return cityDatabase[key];
        }
    }
    // 4. 如果所有方法都失败，返回 null
    console.warn(`所有匹配方法都失败了，无法在数据库中找到与 '${landmarkName}' 相关的位置。`);
    return null;
}
const flyToCommand=(landmark)=>{
   const location = geocode_offline(landmark);
    if (location && viewer) {
      console.log(`执行飞行: 前往 ${landmark}`);
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(location.lon, location.lat, 2500),
        duration: 3
      });
    } else {
      alert("无法执行飞行，数据库中未找到坐标。");
    }
}
const useCommand = data => {
  switch (data.command) {
    case "flyTo":
      flyToCommand(data.parameters.landmark)
      break;
  
    default:
      break;
  }  
};


</script>

<style lang="less" scoped>
.chat-sidebar {
  width: 0;
  height: 100%;
  background-color: var(--bg-sider);
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  border: none;
  overflow: hidden;

  &.no-transition {
    transition: none !important;
  }

  &.sidebar-open {
    width: 850px;
    // max-width: 300px;
    border-right: 1px solid var(--gray-200);
  }

  .sidebar-header {
    height: var(--header-height);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 16px;
    border-bottom: 1px solid var(--gray-200);
    flex-shrink: 0;

    .header-title {
      font-weight: 500;
      font-size: 16px;
      color: var(--gray-900);
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      flex: 1;
    }

    .header-actions {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }

  .conversation-list-top {
    padding: 8px 12px;
    // border-bottom: 1px solid var(--gray-200);
    text-align: center;
    font-size: 18px;
    background-color: blanchedalmond;
    .new-chat-btn {
      width: 100%;
      padding: 8px 12px;
      border-radius: 6px;
      background-color: var(--gray-50);
      color: var(--main-color);
      border: none;
      transition: all 0.2s ease;
      font-weight: 500;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;

      &:hover {
        background-color: var(--main-100);
      }
    }
  }

  .conversation-list {
    flex: 1;
    overflow-y: auto;
    padding: 8px;

    .chat-group {
      margin-bottom: 16px;
    }

    .chat-group-title {
      padding: 4px 8px;
      font-size: 12px;
      color: var(--gray-500);
      font-weight: 500;
      text-transform: uppercase;
    }

    .conversation-item {
      display: flex;
      align-items: center;
      padding: 8px 12px;
      border-radius: 6px;
      margin: 4px 0;
      cursor: pointer;
      transition: background-color 0.2s ease;
      position: relative;
      overflow: hidden;

      .conversation-title {
        flex: 1;
        font-size: 14px;
        color: var(--gray-800);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        transition: color 0.2s ease;
      }

      .actions-mask {
        position: absolute;
        right: 0;
        top: 0;
        bottom: 0;
        width: 60px;
        background: linear-gradient(to right, transparent, var(--bg-sider) 20px);
        opacity: 0;
        transition: opacity 0.3s ease;
        pointer-events: none;
      }

      .conversation-actions {
        display: flex;
        align-items: center;
        position: absolute;
        right: 8px;
        top: 50%;
        transform: translateY(-50%);
        opacity: 0;
        transition: opacity 0.3s ease;

        .more-btn {
          color: var(--gray-600);
          background-color: transparent !important;
          &:hover {
            color: var(--main-500);
            background-color: transparent !important;
          }
        }
      }

      &:hover {
        background-color: var(--gray-50);

        .actions-mask {
            background: linear-gradient(to right, transparent, var(--gray-100) 20px);
        }

        .actions-mask, .conversation-actions {
          opacity: 1;
        }
      }

      &.active {
        background-color: var(--gray-100);

        .conversation-title {
          color: var(--main-600);
          font-weight: 500;
        }
        .actions-mask {
          background: linear-gradient(to right, transparent, var(--gray-100) 20px);
        }
      }
    }

    .empty-list {
      text-align: center;
      margin-top: 20px;
      color: var(--gray-500);
      font-size: 14px;
    }
  }
}
.cesiumContainer {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

.header {
  position: absolute;
  top: 45px;
  left: 0;
  width: 100%;
}
@mixin font-color() {
  background: linear-gradient(0deg, #b9cfff 0%, #fff 99%);
  background-clip: text;
  -webkit-text-fill-color: transparent;
}
@keyframes text-roll {
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(-100%);
  }
}
@keyframes light-go {
  from {
    left: 100px;
  }
  to {
    left: 500px;
    opacity: 0;
  }
}
.layout-header {
  width:100%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  background-color: rgb(2, 23, 46);
  background-image: url(@/assets/img/title_bg.png);
  background-repeat: no-repeat;
  background-position: center top;
  background-size: 100% 100%;
  &::after {
    position: absolute;
    bottom: -55px;
    left: 500px;
    width: 100%;
    width: 500px;
    height: 100px;
    content: "";
    background-image: url(@/assets/img/light_bg.png);
    background-repeat: no-repeat;
    background-size: contain;
    animation: light-go 3s ease-in-out infinite forwards;
  }
  .header-midden {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    overflow-x: hidden;
    font-family: DouYu;
    color: #fff;
    .cn {
      font-size: 18px;
      @include font-color;
    }
    .en {
      position: relative;
      font-size: 10px;
      @include font-color;
    }
  }
  .header-left {
    position: absolute;
    top: 10px;
    left: 30px;
    display: flex;
    grid-gap: 6px;
    align-items: center;
    font-size: 18px;
    color: #fff;
    .message {
      display: flex;
      width: 400px;
      overflow: hidden;
      font-size: 16px;
      &::after {
        width: auto;
        text-wrap: nowrap;
        content: attr(content);
        animation: text-roll 20s linear infinite;
        @include font-color;
      }
    }
  }
  .header-right {
    position: absolute;
    top: 20px;
    right: 30px;
    display: flex;
    grid-gap: 20px;
    font-size: 16px;
    color: #fff;
    span {
      position: relative;
      display: flex;
      align-items: center;
      text-shadow: 0 3px 2px #84a8f663;
      @include font-color;
      &:not(:last-child)::after {
        position: absolute;
        right: -10px;
        width: 2px;
        height: 10px;
        content: "";
        background-color: #fff;
        opacity: 0.2;
      }
    }
  }
}


.message-md {
  margin: 8px 0;
}

.message-md .md-editor-preview-wrapper {
  max-width: 100%;
  padding: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Noto Sans SC', 'PingFang SC', 'Noto Sans SC', 'Microsoft YaHei', 'Hiragino Sans GB', 'Source Han Sans CN', 'Courier New', monospace;

  #preview-only-preview {
    font-size: 1rem;
    line-height: 1.75;
    color: var(--gray-2000);
  }


  h1, h2 {
    font-size: 1.2rem;
  }

  h3, h4 {
    font-size: 1.1rem;
  }

  h5, h6 {
    font-size: 1rem;
  }

  strong {
    font-weight: 600;
  }

  li > p, ol > p, ul > p {
    margin: 0.25rem 0;
  }

  ol, ul {
    padding-left: 1rem;
  }

  cite {
    font-size: 12px;
    color: var(--gray-700);
    font-style: normal;
    background-color: var(--gray-200);
    border-radius: 4px;
    outline: 2px solid var(--gray-200);
  }

  a {
    color: var(--main-700);
  }

  code {
    font-size: 13px;
    font-family: 'Menlo', 'Monaco', 'Consolas', 'PingFang SC', 'Noto Sans SC', 'Microsoft YaHei', 'Hiragino Sans GB', 'Source Han Sans CN', 'Courier New', monospace;
    line-height: 1.5;
    letter-spacing: 0.025em;
    tab-size: 4;
    -moz-tab-size: 4;
    background-color: var(--gray-100);
  }

  p:last-child {
    margin-bottom: 0;
  }
}

.chat-box.font-smaller #preview-only-preview {
  font-size: 14px;

  h1, h2 {
    font-size: 1.1rem;
  }

  h3, h4 {
    font-size: 1rem;
  }
}

.chat-box.font-larger #preview-only-preview {
  font-size: 16px;

  h1, h2 {
    font-size: 1.3rem;
  }

  h3, h4 {
    font-size: 1.2rem;
  }

  h5, h6 {
    font-size: 1.1rem;
  }

  code {
    font-size: 14px;
  }
}
.homepage{
  position: absolute;
    width: 100%;
}
.tree, .queryBtn{
   position: absolute;
  // top: 20vh;
  // left: 10px;
}
.queryCtn{
   position: absolute;
}
.toggle-button{
  top:40vh
}
.queryBtn{
  top:40vh;
  right: 0;
}
</style>
